package sddz.foodmanage.base;

import android.Manifest;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.zhy.autolayout.AutoLayoutActivity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import sddz.foodmanage.R;


/**
 * Created by zhanglei on 2017/3/24 0024.
 * Activity基类
 */

public class BaseActivity extends AutoLayoutActivity {

    protected AppCompatActivity mActivity;
    protected ProgressDialog dialog;




    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mActivity = this;
        dialog = new ProgressDialog(mActivity);
        dialog.setMessage("加载中...");
        if (getSupportActionBar() != null){
            getSupportActionBar().hide();
        }
    }
    protected void showDialog() {
        dialog.show();
    }

    protected void showDialog(String message) {
        dialog.setMessage(message);
        dialog.show();
    }

    protected void hideDialog() {
        dialog.dismiss();
    }

    protected void show(String message) {
        Toast.makeText(mActivity, message, Toast.LENGTH_SHORT).show();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.e("BaseActivity",mActivity.getClass().getSimpleName());
    }

    /**
     * 设置界面透明度
     *
     * @param alpha
     */
    protected void setAlpha(float alpha) {
        Window window = getWindow();
        WindowManager.LayoutParams attributes = window.getAttributes();
        attributes.alpha = alpha;
        window.setAttributes(attributes);
    }

    protected void hideKeyboard(View view){
        //隐藏软键盘
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        // 获取软键盘的显示状态
        boolean isOpen = imm.isActive();
        if (isOpen) {
            // 隐藏软键盘
            imm.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 判断GPS是否开启，GPS或者AGPS开启一个就认为是开启的
     *
     * @return true 表示开启
     */
    public boolean isOPen() {
        LocationManager locationManager
                = (LocationManager) mActivity.getSystemService(Context.LOCATION_SERVICE);
        // 通过GPS卫星定位，定位级别可以精确到街（通过24颗卫星定位，在室外和空旷的地方定位准确、速度快）
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        // 通过WLAN或移动网络(3G/2G)确定的位置（也称作AGPS，辅助GPS定位。主要用于在室内或遮盖物（建筑群或茂密的深林等）密集的地方定位）
        boolean network = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (gps || network) {
            return true;
        }

        return false;
    }

    /**
     * 强制帮用户打开GPS
     */
    public void openGPS() {
        Intent GPSIntent = new Intent();
        GPSIntent.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");
        GPSIntent.addCategory("android.intent.category.ALTERNATIVE");
        GPSIntent.setData(Uri.parse("custom:3"));
        try {
            PendingIntent.getBroadcast(mActivity, 0, GPSIntent, 0).send();
        } catch (PendingIntent.CanceledException e) {
            e.printStackTrace();
        }
    }

    /**
     * 开启一个Fragment
     *
     * @param fragment
     */
    protected void openFragment(Fragment fragment, int layoutId) {
        //开启事务
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        //设置动画效果
        transaction.setCustomAnimations(R.anim.translate_right_info_anim, R.anim.translate_right_exit_anim,
                R.anim.translate_right_info_anim, R.anim.translate_right_exit_anim);
        //将Fragment添加到事务当中
        transaction.add(layoutId, fragment);
        //将Fragment添加到回退栈
        transaction.addToBackStack("");
        //提交事务
        transaction.commit();
    }
    /**
     * 打开一个带动画的fragment，并将其添加到回退栈
     *
     * @param fragment
     * @param layoutId
     */
    protected void addFragmentAndAnim(Fragment fragment, int layoutId) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();
        transaction.setCustomAnimations(R.anim.right_enter_anim, R.anim.right_exit_anim, R.anim.right_enter_anim, R.anim.right_exit_anim);
        transaction.add(layoutId, fragment);
        transaction.addToBackStack("task");
        transaction.commit();
    }

    /**
     * 找到控件
     *
     * @param viewId
     * @param <T>
     * @return
     */
    protected <T extends View> T getView(Integer viewId) {
        return (T) findViewById(viewId);
    }

    /**
     * 检查是否有该权限
     *
     * @param permission
     * @return
     */
    public boolean isPermission(String permission) {
        return (ContextCompat.checkSelfPermission(mActivity, permission)
                == PackageManager.PERMISSION_GRANTED);
    }

    /**
     * 申请应用授权
     *
     * @param permissions 权限数组（同一组权限的）
     */
    protected void applyPermission(String[] permissions, final PermissionListener listener) {
        applyPermission(permissions, 0x100, listener);
    }

    /**
     * 申请应用授权
     *
     * @param permissions 权限数组（同一组权限的）
     */
    protected void applyPermission(String[] permissions, int code, final PermissionListener listener) {
        //是否需要动态申请权限
        if (Build.VERSION.SDK_INT >= 23) {
            AndPermission.with(mActivity)
                    .requestCode(code)
                    .permission(permissions)
                    .callback(new PermissionListener() {

                        @Override
                        public void onSucceed(int requestCode, @android.support.annotation.NonNull List<String> grantPermissions) {
                            if (listener != null) {
                                listener.onSucceed(requestCode, grantPermissions);
                            }
                        }

                        @Override
                        public void onFailed(int requestCode, @android.support.annotation.NonNull List<String> deniedPermissions) {
                            if (listener != null) {
                                listener.onFailed(requestCode, deniedPermissions);
                            }
                        }
                    }).start();
        }
    }


}
